import 'package:async/src/result/result.dart';
import 'package:boss/color_constant.dart';
import 'package:boss/main.dart';
import 'package:boss/models/vice_screen.dart';
import 'package:boss/provider/login_user_provider.dart';
import 'package:boss/textStyle/text_style.dart';
import 'package:boss/ui/widget/alert/alert.dart';
import 'package:boss/ui/widget/button/fixed_bottom_btn.dart';
import 'package:boss/ui/widget/center_title_app_bar.dart';
import 'package:boss/ui/widget/custom_list_title.dart';
import 'package:boss/ui/widget/form/base_text_form_field.dart';
import 'package:boss/ui/widget/image/base_image.dart';
import 'package:boss/ui/widget/label_button.dart';
import 'package:boss/ui/widget/loader/loader.dart';
import 'package:boss/ui/widget/loading/loading.dart';
import 'package:boss/ui/widget/picker/imagePicker/image_picker.dart';
import 'package:drag_list/drag_list.dart';
import 'package:flutter/material.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:hi_common/hi_common.dart';
import 'package:provider/provider.dart';
import 'package:router/annotation.dart';
import 'package:flustars/flustars.dart' as flustars;

@RouterConfig(ViceScreenPage.pageName)
class ViceScreenPage extends StatefulWidget {
  static const pageName = '/ViceScreenPage';

  @override
  _ViceScreenPageState createState() => _ViceScreenPageState();
}

class _ViceScreenPageState extends BaseState<ViceScreenPage> {
  _ViceScreenPageState() : super(ViceScreenPage.pageName);

  ViceScreen data;

  List<String> adList = [];

  final Map<String, int> fileMap = {};

  final totalMemory = 50 * 1024 * 1024;

  int get usedMemory {
    int usedMemory = 0;
    fileMap.values.forEach((element) {
      usedMemory += element;
    });

    return usedMemory;
  }

  String get memoryText {
    return '${((totalMemory - usedMemory) / 1024.0 / 1024.0).toStringAsFixed(2)}MB可用（共50MB）';
  }

  bool isAdEdit = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CenterTitleAppBar(title: '双屏设置'),
      body: Loader<ViceScreen>(
        loadTask: loadTask,
        builder: (context) {
          return Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Expanded(
                child: SingleChildScrollView(
                  padding: EdgeInsets.zero,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Container(
                        width: double.infinity,
                        padding: EdgeInsets.all(20.w),
                        color: ColorConstant.e5e5,
                        child: Text('该设置只适用于双屏收银机', style: TextStyleConstant().normal_3_28),
                      ),
                      Container(
                        padding: EdgeInsets.only(bottom: 20.w),
                        alignment: Alignment.center,
                        color: ColorConstant.e5e5,
                        child: Text('副屏预览', style: TextStyleConstant().normal_1_36),
                      ),
                      Container(
                        height: 320.w,
                        color: ColorConstant.e5e5,
                        child: Stack(
                          children: [
                            if (adList.length > 0)
                              Swiper(
                                key: UniqueKey(),
                                autoplay: adList.length > 1,
                                itemCount: adList.length,
                                itemHeight: 320.w,
                                itemBuilder: (context, index) {
                                  return BaseImage(adList[index]);
                                },
                              ),
                            Positioned(
                              top: 20.w,
                              left: 20.w,
                              child: Row(
                                children: [
                                  if (data.storeLogo != null)
                                    Container(
                                      margin: EdgeInsets.only(right: 10.w),
                                      child: BaseImage(
                                        data.storeLogo,
                                        width: 80.w,
                                        height: 80.w,
                                        borderRadius: BorderRadius.circular(40.w),
                                      ),
                                    ),
                                  if (data.storeName != null) Text(data.storeName, style: TextStyleConstant().normal_1_32),
                                ],
                              ),
                            ),
                          ],
                        ),
                      ),
                      Container(
                        padding: EdgeInsets.symmetric(horizontal: 20.w),
                        child: BaseTextFormField(
                          prefixText: '门店名称',
                          hintText: '请输入',
                          initialValue: data.storeName,
                          onChanged: (value) {
                            setState(() {
                              data.storeName = value;
                            });
                          },
                        ),
                      ),
                      Container(
                        padding: EdgeInsets.symmetric(horizontal: 20.w),
                        child: CustomListTitle(
                          title: '门店头像',
                          trailing: GestureDetector(
                            onTap: () async {
                              var image = await ImagePicker.pickImage(context);
                              if (image != null) {
                                var url = await UploadUtil.uploadImage(image);
                                if (url != null) {
                                  setState(() {
                                    data.storeLogo = url;
                                  });
                                }
                              }
                            },
                            child: BaseImage(
                              data.storeLogo,
                              width: 80.w,
                              height: 80.w,
                              borderRadius: BorderRadius.circular(40.w),
                            ),
                          ),
                        ),
                      ),
                      Container(
                        margin: EdgeInsets.all(20.w),
                        child: Text('门店logo会在双屏上显示，不上传则展示默认图片', style: TextStyleConstant().normal_3_28),
                      ),
                      Container(
                        padding: EdgeInsets.symmetric(horizontal: 20.w),
                        child: CustomListTitle(
                          title: '轮播广告图',
                          trailing: LabelButton(
                            title: isAdEdit ? '完成' : '编辑',
                            padding: EdgeInsets.only(top: 4, bottom: 4, left: 8),
                            onTap: () {
                              setState(() {
                                isAdEdit = !isAdEdit;
                              });
                            },
                          ),
                        ),
                      ),
                      Container(
                        padding: EdgeInsets.all(20.w),
                        child: Text(memoryText, style: TextStyleConstant().normal_3_28),
                      ),
                      if (!isAdEdit)
                        Container(
                          height: 140.w,
                          child: ListView.builder(
                            scrollDirection: Axis.horizontal,
                            padding: EdgeInsets.only(left: 20.w),
                            itemBuilder: (context, index) {
                              if (index == adList.length) {
                                return GestureDetector(
                                  onTap: () async {
                                    var image = await ImagePicker.pickImage(context);
                                    if (image != null) {
                                      var url = await UploadUtil.uploadImage(image);
                                      if (url != null) {
                                        final size = await image.length();
                                        setState(() {
                                          adList.insert(0, url);
                                          fileMap[url] = size;
                                        });
                                      }
                                    }
                                  },
                                  child: Padding(
                                    padding: EdgeInsets.all(10.w),
                                    child: Container(
                                      width: 200.w,
                                      alignment: Alignment.center,
                                      decoration: BoxDecoration(border: Border.all(color: ColorConstant.ffcc, width: 1.px)),
                                      child: BaseImage(
                                        'assets/image/small_plus_icon.png',
                                        width: 80.w,
                                        height: 80.w,
                                      ),
                                    ),
                                  ),
                                );
                              }

                              final current = adList[index];

                              return buildAd(current);
                            },
                            itemCount: adList.length + 1,
                          ),
                        ),
                      if (isAdEdit)
                        Container(
                          height: 140.w,
                          padding: EdgeInsets.only(left: 20.w),
                          child: DragList<String>.handleless(
                            items: adList,
                            itemExtent: 220.w,
                            scrollDirection: Axis.horizontal,
                            onItemReorder: (from, to) {
                              setState(() {
                                adList.insert(to, adList.removeAt(from));
                              });
                            },
                            builder: (context, data) {
                              return Stack(
                                children: [
                                  buildAd(data),
                                  if (isAdEdit)
                                    Positioned(
                                      top: -4.w,
                                      right: -4.w,
                                      child: GestureDetector(
                                        child: Padding(
                                          padding: EdgeInsets.all(4.w),
                                          child: Container(
                                            width: 30.w,
                                            height: 30.w,
                                            decoration: BoxDecoration(
                                              color: Colors.black45,
                                              shape: BoxShape.circle,
                                            ),
                                            child: Icon(
                                              Icons.close,
                                              color: Colors.white,
                                              size: 24.sp,
                                            ),
                                            alignment: Alignment.center,
                                          ),
                                        ),
                                        onTap: () {
                                          showAlert(
                                            context,
                                            content: '确认删除该图吗？',
                                            onConfirm: (context) {
                                              Navigator.pop(context);

                                              setState(() {
                                                adList.remove(data);
                                              });
                                            },
                                            onCancel: (context) {
                                              Navigator.pop(context);
                                            },
                                          );
                                        },
                                        behavior: HitTestBehavior.translucent,
                                      ),
                                    ),
                                ],
                              );
                            },
                          ),
                        ),
                    ],
                  ),
                ),
              ),
              FixedBottomBtn(
                title: '保存',
                onTap: save,
              ),
            ],
          );
        },
      ),
    );
  }

  Widget buildAd(String img) {
    return Container(
      padding: EdgeInsets.all(10.w),
      child: BaseImage(
        img,
        width: 200.w,
        height: 120.w,
      ),
    );
  }

  Future<Result<ViceScreen>> loadTask() async {
    final res = await api.queryStoreViceScreen();
    if (!res.successful()) {
      return Result.error(res.msg);
    }
    var loginUserProvider = Provider.of<LoginUserProvider>(GlobalPageContext.instance.context, listen: false);

    data = res.data ?? ViceScreen.fromJson({});
    if (flustars.TextUtil.isEmpty(data.storeName)) {
      data.storeName = loginUserProvider.loginUser.storeName;
    }

    adList = res.data?.adUrl?.split('|') ?? [];

    checkStoreLogo();

    return Result.value(res.data);
  }

  void checkStoreLogo() async {
    if (flustars.TextUtil.isEmpty(data.storeLogo)) {
      var loginUserProvider = Provider.of<LoginUserProvider>(GlobalPageContext.instance.context, listen: false);
      var response = await api.getStoreMessage(loginUserProvider.loginUser.storeId);
      if (response.successful()) {
        setState(() {
          data.storeLogo = response.data.storeHeadImage;
        });
      }
    }
  }

  void save() async {
    if (flustars.TextUtil.isEmpty(data.storeName)) {
      toast('请输入门店名称');
      return;
    }

    if (data.storeName.length > 20) {
      toast('门店名称长度不能超过20');
      return;
    }
    try {
      showLoadingToast();

      data.adUrl = adList.join('|');
      final res = await api.updateStoreViceScreen(data);
      if (!res.successful()) {
        toast(res.msg);
        return;
      }
      data = res.data;

      toast('修改成功');

      print('*' * 20);
    } catch (e) {
      toast(e.toString());
    } finally {
      hideLoadingToast();
    }
  }
}
